<template>

  <button @click="downloadExcel">下载 Excel 文件</button>
</template>

<script>
import axios from 'axios';
import { saveAs } from 'file-saver';

export default {
  methods: {
    async downloadExcel() {
      try {
        const response = await axios({
          url: 'http://localhost:8080/pileData/createPouringTable?id=1', // 替换为实际的服务器 API 地址
          method: 'GET',
          responseType: 'blob', // 设置响应类型为 blob
        });

        const contentDisposition = response.headers['content-disposition'];
        let filename = 'downloaded_file.xlsx';
        if (contentDisposition) {
          const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
          if (filenameMatch != null && filenameMatch[1]) {
            filename = filenameMatch[1].replace(/['"]/g, '');
          }
        }

        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        saveAs(blob, filename);
      } catch (error) {
        console.error('下载文件时出错:', error);
      }
    },
  },
};
</script>